package com.example.vuedemo.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.vuedemo.entity.SpUser;
import com.example.vuedemo.service.SpUserService;
import com.example.vuedemo.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author 刘传政
 * @since 2021-09-08
 */
@RestController
@RequestMapping("/vuedemo/sp-user")
@CrossOrigin //解决跨域问题
public class SpUserController {
    @Autowired
    SpUserService userService;
    //项目启动的情况下访问 http://localhost:8001/swagger-ui.html 就能打开swagger接口文档，并能修改传值，发送请求
    @GetMapping("/list")
    public R list(@RequestParam(required = false) String query, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit) {
        //1.构建分页查询对象
        Page<SpUser> usersPage = new Page(page,limit);

        //2.构建查询条件
        QueryWrapper<SpUser> wrapper = new QueryWrapper();
        wrapper.orderByDesc("create_time");

        if(!StringUtils.isEmpty(query)){
            wrapper.like("username",query);
        }

        userService.page(usersPage,wrapper);
        long total = usersPage.getTotal();
        List<SpUser> records = usersPage.getRecords();

//        Map<String,Object> data = new HashMap<>();
//        data.put("total",total);
//        data.put("records",records);

        //R r = R.ok();
        //      R r = R.ok().data("total",total);
        return R.ok().data("total",total).data("records",records);
    }
    @PostMapping("/userStatusChange/{userId}/{status}")
    public R userStatusChange(@PathVariable Integer userId,
                              @PathVariable Boolean status){

        SpUser user = userService.getById(userId);
        user.setStatus(status);

        userService.updateById(user);
        return R.ok();
    }

    @PostMapping("/save")
    public R addUser(@RequestBody SpUser user){
        user.setCreateTime(new Date());
        userService.save(user);
        System.out.println(user);
        return R.ok();
    }

    @GetMapping("/findUserById/{userId}")
    public R findUserById(@PathVariable Integer userId){
        System.out.println(userId);
        SpUser user = userService.getById(userId);
        return R.ok().data("user",user);
    }

    @PostMapping("/update")
    public R updateUser(@RequestBody SpUser user){
        user.setUpdateTime(new Date());
        userService.updateById(user);
        return R.ok();
    }

    @PostMapping("/delete/{userId}")
    public R deleteById(@PathVariable Integer userId){
        userService.removeById(userId);
        return R.ok();
    }
}

